package com.raymond.queue.client.codec.encodeing;

import com.raymond.queue.common.codec.BaseCodecStrategy;
import com.raymond.queue.common.codec.annotation.MsgCodec;
import com.raymond.queue.common.codec.encodeing.BaseEncoder;
import com.raymond.queue.common.enums.CommandIdType;
import com.raymond.queue.common.msg.BaseMessage;
import com.raymond.queue.common.msg.MsgHead;
import com.raymond.queue.common.msg.request.PackRequest;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;

import java.util.List;

/**
 * 打包请求编码
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-07-19 11:39
 */
@MsgCodec(commandId = CommandIdType.PACK_REQ)
public class PackRequestEncoder extends BaseEncoder {
    @Override
    public byte[] encode0(BaseMessage msg) throws Exception {
        PackRequest request = (PackRequest) msg;
        List<BaseMessage> list = request.getList();
        ByteBuf buffer = Unpooled.buffer();
        buffer.writeInt(list.size());
        int byteTotalLen = 4;
        for (BaseMessage baseMessage : list) {
            byte[] body = BaseCodecStrategy.getBaseEncoder(baseMessage.getCommandId()).encode0(baseMessage);
            int byteLen = body.length + MsgHead.getHeadLength();
            buffer.writeInt(byteLen);
            buffer.writeInt(baseMessage.getCommandId());
            buffer.writeInt(baseMessage.getSequenceId());
            buffer.writeBytes(body);
            byteTotalLen += byteLen;
        }
        byte[] body = new byte[byteTotalLen];
        buffer.readBytes(body);
        return body;
    }
}
